----------------------------------------------------------------
-- Global Variables
----------------------------------------------------------------

AuctionListWindow =
{
    TEST_DATA_ON = false,
    REQUEST_TEST_RESULTS_ON = false,
    DEBUG_ON = false,
    DEBUG_LEVEL = 7,
    
    
    -- Note: most variable data is now kept in AuctionListDataManager
    
    -------------
    -- Strings --
    titleBarText			= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_WINDOW_TITLE ),
    noResultsText			= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_NO_AUCTION_FOUND ),
    
    bidMissingText          = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_BID_MISSING_PLACEHOLDER ),
    buyOutMissingText       = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_BUY_OUT_MISSING_PLACEHOLDER ),
    playerIsHighBidderText  = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_PLAYER_IS_HIGH_BIDDER_TEXT ),
    
    bidText					= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_NEXT_BID_LABEL ),
    moneyAvailableText		= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_MONEY_AVAILABLE_LABEL ),
    
    -- Buttons
    bidButtonText			= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_BID_BUTTON ),
    buyOutButtonText		= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_BUY_OUT_BUTTON ),
    cancelButtonText		= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_CANCEL_BUTTON ),
    
    myAuctionDefaultText	= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HINT_TEXT_AUCTIONS_DEFAULT ),
    myAuctionCancelText		= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HINT_TEXT_CANCEL_AUCTION ),
    myAuctionNoCancelText	= GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_HINT_TEXT_CANNOT_CANCEL_AUCTION ),

	warnBeforeCancellingText = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_CANCEL_CONFIRMATION_TEXT ),
	
    -- error strings
    errorInsufficientFundsText = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_INSUFFICIENT_FUNDS ),
    errorServerUnavailableText = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_SERVER_UNAVAILABLE ),
     
     
    -- Time Remaining Strings 
    
	--[[	
	--SEARCH_RESULTS_TIME_LEFT_TOOLTIP_HOURS	<<1>> to <<2>> hours remaining

    TOOLTIP_TIME_LEFT_MEDIUM    = GetFormatStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_HOURS, {     TIME_SHORT,     TIME_MEDIUM } )
    TOOLTIP_TIME_LEFT_LONG      = GetFormatStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_HOURS, {     TIME_MEDIUM,     TIME_LONG } )
    TOOLTIP_TIME_LEFT_VERY_LONG = GetFormatStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_HOURS, {     TIME_LONG,     TIME_MAXIMUM } )
	--]]
	
    TEXT_TIME_LEFT_SHORT        = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TEXT_SHORT ),
    TEXT_TIME_LEFT_MEDIUM       = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TEXT_MEDIUM ),
    TEXT_TIME_LEFT_LONG         = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TEXT_LONG ),
    TEXT_TIME_LEFT_VERY_LONG    = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TEXT_VERY_LONG ),

    TOOLTIP_TIME_LEFT_SHORT     = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_SHORT ),
    TOOLTIP_TIME_LEFT_MEDIUM    = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_MEDIUM ),
    TOOLTIP_TIME_LEFT_LONG      = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_LONG ),
    TOOLTIP_TIME_LEFT_VERY_LONG = GetStringFromTable( "AuctionHouseStrings",  StringTables.AuctionHouse.SEARCH_RESULTS_TIME_LEFT_TOOLTIP_VERY_LONG ),
     
     
    ---------------
    -- Constants --
    --MAX_VISIBLE_ROWS = 8,
    MAX_VISIBLE_ROWS = 6,
    HEIGHT_PER_ROW = 65,
    LIST_WIDTH = 1065,
    
    UNSORTED = 0,
    DEFAULT_SORTING = true,     -- true for alphabetical/numeric/increasing order
                                -- false for reverse order
    
    MIN_BID_INCREMENT = 1,
    
    --  these values should really be Lua Exposed vars or at least kept in the
    --    same place as where auction durations are declared
    TIME_SHORT = 1,
    TIME_MEDIUM = 4,
    TIME_LONG = 10,
    TIME_MAXIMUM = 18,
    
    COLOR_MEETS_REQUIREMENTS = DefaultColor.TOOLTIP_MEETS_REQUIREMENTS,
    COLOR_FAILS_REQUIREMENTS = DefaultColor.TOOLTIP_FAILS_REQUIREMENTS,
        
    ANCHOR_CURSOR    = { Point = "topleft", RelativeTo = "CursorWindow", RelativePoint = "bottomleft", XOffset = 30, YOffset = -20 },    
    
    -- TimeLeft table - holds text, tooltip, and value used for time remaining.
    -- Initialized dynamically so that these values can be sent from the server in the future
    TimeLeft = {},

	TimeLeftValueNotFound = -1,	-- don't use 0 - it's a legal value
    
    
    -------------
    -- Options --
    
    HideBidPriceIfBuyOnly = false,
    
    MIN_BID_MULTIPLIER = 0.01,  -- NOTE: we may later want to make this a user setting
                                --  instead of a constant
    
    
}

local ALW = AuctionListWindow


----------------------------------------------------------------
-- Local Functions
----------------------------------------------------------------

local function SendDebug( text, level )
	level = level or 5
	
    if AuctionListWindow.DEBUG_ON and level >= AuctionListWindow.DEBUG_LEVEL then
        DEBUG( text )
    end
end



----------------------------------------------------------------
-- Local Variables
----------------------------------------------------------------

local windowName = "AuctionHouseWindowSearchResults"



----------------------------------------------------------------
-- AuctionListWindow Functions
----------------------------------------------------------------


-- called directly by AuctionHouseWindow.Initialize()
function AuctionListWindow.Initialize()
SendDebug(L"AuctionListWindow.Initialize")

    --local windowData = AuctionListDataManager.GetCurrentWindowData()
    
    WindowRegisterEventHandler (windowName, SystemData.Events.PLAYER_MONEY_UPDATED, "AuctionListWindow.UpdateMoneyAvailable" )
    WindowRegisterEventHandler (windowName, SystemData.Events.AUCTION_BID_RESULT_RECEIVED, "AuctionListWindow.ReceivedBidResult" )

    -- Set all static data    
    LabelSetText( windowName.."TitleBarText", AuctionListWindow.titleBarText )
    LabelSetText( windowName.."NoResultsText", AuctionListWindow.noResultsText )
    WindowSetShowing( windowName.."NoResultsText", false )
    
    -- Windows for Browse and My Bids tabs
	LabelSetText( windowName.."BrowseOptionsMyBidPriceHeader", AuctionListWindow.bidText )
	LabelSetText( windowName.."BrowseOptionsMoneyAvailableHeader", AuctionListWindow.moneyAvailableText )
    ButtonSetText( windowName.."BrowseOptionsBidButton", AuctionListWindow.bidButtonText )
    ButtonSetText( windowName.."BrowseOptionsBuyOutButton", AuctionListWindow.buyOutButtonText )
    
    -- Windows for My Auctions tab
    LabelSetText( windowName.."MyAuctionsOptionsHelpText", AuctionListWindow.myAuctionDefaultText )
    ButtonSetText( windowName.."MyAuctionsOptionsCancelButton", AuctionListWindow.cancelButtonText )

    local listHeight = (AuctionListWindow.MAX_VISIBLE_ROWS * AuctionListWindow.HEIGHT_PER_ROW)
	WindowSetDimensions( windowName.."List", AuctionListWindow.LIST_WIDTH, listHeight )
	
    AuctionListWindow.SelectTab( AuctionListDataManager.currentTab )
    
    AuctionListWindow.SetListRowTints()

        -- Clear all Sort Buttons


-- DEBUG: only need this next line if window starts off visible 
--AuctionListWindow.UpdateMoneyAvailable()
    
    -- Reset dynamic data
    AuctionListWindow.Clear()
    
-- DEBUG
if AuctionListWindow.TEST_DATA_ON then
	AuctionListWindow.InitializeTimeLeftValues()
    AuctionListWindow.TEST_CreateTestData()
end
-- END DEBUG

SendDebug(L"finished AuctionListWindow.Initialize")
end



-- This is moved into a function and initialized dynamically so that 
--   these values can be sent from the server in the future
--
function AuctionListWindow.InitializeTimeLeftValues()

	ALW.TimeLeft =
	{ 
		-- keep in order with shortest first
		{   text = ALW.TEXT_TIME_LEFT_SHORT,     value = GameData.Auction.DURATION_INDEX_SHORT,     tooltip = ALW.TOOLTIP_TIME_LEFT_SHORT,     }, 
		{   text = ALW.TEXT_TIME_LEFT_MEDIUM,    value = GameData.Auction.DURATION_INDEX_MEDIUM,    tooltip = ALW.TOOLTIP_TIME_LEFT_MEDIUM,    },  
		{   text = ALW.TEXT_TIME_LEFT_LONG,      value = GameData.Auction.DURATION_INDEX_LONG,		tooltip = ALW.TOOLTIP_TIME_LEFT_LONG,      }, 
		{   text = ALW.TEXT_TIME_LEFT_VERY_LONG, value = GameData.Auction.DURATION_INDEX_VERY_LONG, tooltip = ALW.TOOLTIP_TIME_LEFT_VERY_LONG, }, 
	}
	
	ALW.DefaultTimeLeftText = ALW.TEXT_TIME_LEFT_VERY_LONG
	ALW.DefaultTimeLeftTooltip = ALW.TOOLTIP_TIME_LEFT_VERY_LONG

end


function AuctionListWindow.SelectTab( tabNumber )
	SendDebug(L"AuctionListWindow.SelectTab tabNumber="..tabNumber, 4)
	
	-- change the bottom buttons if changing to/from My Auctions Pane
	local isMyAuctionsPane = AuctionListDataManager.IsMyAuctionsPaneShowing()
	
	-- only need to change if isn't showing the appropriate buttons
	if isMyAuctionsPane ~= WindowGetShowing( windowName.."MyAuctionsOptions") then
		WindowSetShowing( windowName.."MyAuctionsOptions", isMyAuctionsPane )
		WindowSetShowing( windowName.."BrowseOptions", not isMyAuctionsPane )
	end

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    for i, data in ipairs( windowData.columnData ) do
		
	--SendDebug(L"    data.text="..data.text, 9)
        local buttonName = windowName.."Header"..data.column
        local sortColumnSelected = (i == windowData.sortColumnNum)
	    ButtonSetText( buttonName, data.text )
        WindowSetShowing( buttonName.."DownArrow", (sortColumnSelected and windowData.shouldSortIncresing) )
        WindowSetShowing( buttonName.."UpArrow", (sortColumnSelected and not windowData.shouldSortIncresing) )
    end
    	
    AuctionListWindow.DisplayCurrentWindowData()
    AuctionListWindow.UpdateButtons()
end


function AuctionListWindow.TEST_CreateTestData()
SendDebug(L"AuctionListWindow.TEST_CreateTestData")
    
    
    local testData = {}
    local inventory = DataUtils.GetItems()
    
    if inventory == nil then
        SendDebug(L"AuctionListWindow.TEST_CreateTestData - no backpack data found")
        return
    end
    
    local firstSlotToCheck = 2
    local slotsToCheck = math.random( 1, 20 )
    -- we're looking at up to 20 backpack slots starting at firstSlotToCheck
    for inventorySlot = firstSlotToCheck, (firstSlotToCheck+slotsToCheck) do
        local itemData = inventory[inventorySlot]
        if itemData ~= nil and itemData.name ~= L"" then
            local newAuction = AuctionListWindow.TEST_CreateTestAuction( itemData )
            table.insert( testData, newAuction )
        end
    end
    
    AuctionHouseWindow.OnSearchResultsReceived( testData )
end


function AuctionListWindow.TEST_CreateTestAuction( itemData )
SendDebug(L"AuctionListWindow.TEST_CreateTestAuction for "..itemData.name)
    local auctionData = {}
    
    auctionData.itemData = itemData
    
    local tempName = L"SellerOf"..itemData.name
    tempName = wstring.gsub( tempName, L" ", L"" )
    local stringSize = wstring.len( tempName) 
    local startIndex = math.random( 1, stringSize - 7 )
    local endIndex = math.random( startIndex+1, stringSize )
    if (endIndex - startIndex) > 13 then -- 14 is max character name size
        endIndex = startIndex + 13
    end
    local sellerName =  wstring.sub( tempName, startIndex, endIndex )
    
    auctionData.sellerName = sellerName
    auctionData.highBidderName = wstring.reverse( sellerName )
    
    local currentTab = AuctionListDataManager.GetCurrentTabNumber()
    if currentTab == AuctionHouseWindow.TAB_AUCTIONS_ID then
		chanceOfPlayerSellerBidder = math.random( 1, 2 )
    elseif currentTab == AuctionHouseWindow.TAB_BIDS_ID then
		chanceOfPlayerSellerBidder = math.random( 3, 4 )
    else
		chanceOfPlayerSellerBidder = math.random( 1, 5 )
    end
    if chanceOfPlayerSellerBidder == 1 then
        auctionData.sellerName = GameData.Player.name
        
    elseif chanceOfPlayerSellerBidder == 2 then
        auctionData.sellerName = GameData.Player.name
        auctionData.highBidderName = L""
        
    elseif chanceOfPlayerSellerBidder == 3 then
        auctionData.highBidderName = GameData.Player.name
    end
    
    -- create a random integer with 1 to 9 digits
    local function rand9()
        return( math.floor( math.random() * (10 ^ math.random( 1, 9 ) ) ) )
    end
    
    auctionData.currentBid = rand9()
    
    -- trick items with stack counts to have closer values in most cases,
    --   so we can see if the pricePerCount sorting works
    if( itemData.stackCount > 1 ) then
        auctionData.currentBid = auctionData.currentBid + (10 ^ 7)
    end
    
    local buyOutChoice = math.random( 1, 3 )
    
    if buyOutChoice == 1 then 
        auctionData.buyOutPrice = 0 -- no buyOut option
    
    elseif  buyOutChoice == 2 then  -- no bid option
        auctionData.buyOutPrice = auctionData.currentBid
        
    else                            -- random amount higher than bid price
        auctionData.buyOutPrice = auctionData.currentBid + rand9()
    end
    
    
    auctionData.timeLeft = math.random( 1, (60 * 60 * ALW.TIME_MAXIMUM) )
    
    auctionData.auctionIDHigherNum = rand9()
    auctionData.auctionIDLowerNum = rand9()
    auctionData.revision = rand9()
   
   return auctionData
end

-- END DEBUG: TESTING: remove me 


function AuctionListWindow.OnSearchResultsReceived( searchResultsTable )
SendDebug(L"AuctionListWindow.OnSearchResultsReceived", 9)

    if searchResultsTable == nil then
         ERROR(L"AuctionListWindow.OnSearchResultsReceived ERROR - nil data table")
        return
    end
    
SendDebug(L"  searchResultsTable has "..#searchResultsTable..L" auctions", 9)

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    windowData.displayOrder = {}
    for i = 1, #searchResultsTable do  
        table.insert( windowData.displayOrder, i )
        
        -- remember original ordering
        searchResultsTable[i].originalIndex = i
    end
    
    windowData.reverseDisplayOrder = {}
    for i = #searchResultsTable, 1, -1 do  
        table.insert( windowData.reverseDisplayOrder, i )
    end
    
    windowData.searchResultsData = searchResultsTable
    
    AuctionListWindow.Sort()
	
	AuctionListWindow.DisplayCurrentWindowData()
end

function AuctionListWindow.DisplayCurrentWindowData()
SendDebug(L"AuctionListWindow.DisplayCurrentWindowData")

	local windowData = AuctionListDataManager.GetCurrentWindowData()

    WindowSetShowing( windowName.."NoResultsText", (#windowData.displayOrder == 0) )
    
    if windowData.shouldSortIncresing then
        ListBoxSetDisplayOrder( windowName.."List", windowData.displayOrder )
    else
        ListBoxSetDisplayOrder( windowName.."List", windowData.reverseDisplayOrder )
    end 
end


function AuctionListWindow.Populate()
SendDebug(L"AuctionListWindow.Populate")

    local windowData = AuctionListDataManager.GetCurrentWindowData()
    if (nil == windowData.searchResultsData) then
        SendDebug(L"  no search Results data found!")
    end

    for row, data in ipairs(AuctionHouseWindowSearchResultsList.PopulatorIndices) do
    
SendDebug(L"    updating row # = "..row..L"  data # = "..data)
        local rowName = windowName.."ListRow"..row
        
        local auctionData = windowData.searchResultsData[data]
        if nil == auctionData then
            ERROR(L"AuctionListWindow.Populate ERROR: Auction Data not found")
            continue
        end
        
        local itemData = auctionData.itemData
         if (nil == itemData) then
            ERROR(L"AuctionListWindow.Populate ERROR: Item Data not found")
            continue
        end   
        
        AuctionListWindow.PopulateRow( rowName, auctionData, itemData )
        
	    -- put highlight box around the selected row, if it's visible
	    -- NOTE: this may be a whole list of rows in the future
        local dataIndex = ListBoxGetDataIndex( windowName.."List", row )
        local rowIsSelected = (windowData.currentlySelectedRow == dataIndex)
        
        ButtonSetPressedFlag(rowName,  rowIsSelected)
        ButtonSetStayDownFlag(rowName, rowIsSelected)
        
        if rowIsSelected then
        SendDebug(L"  selected "..StringToWString(rowName) )
            windowData.currentlySelectedRowName = rowName
        end
    end
end


function AuctionListWindow.PopulateRow( rowName, auctionData, itemData )
	--SendDebug(L"AuctionListWindow.PopulateRow"..StringToWString(rowName) , 7)
    
    local color

    -- Icon
    local buttonName = rowName.."Icon"
    local texture, x, y = GetIconData(itemData.iconNum)
    DynamicImageSetTexture( buttonName.."Icon", texture, x, y)
    
    -- Stack Count on Icon            
    if( itemData.stackCount > 1 ) then
        ButtonSetText(buttonName, L""..itemData.stackCount )
        SendDebug(L"AuctionListWindow.PopulateRow"..StringToWString(rowName) , 7)
		SendDebug(L"   stackcount="..StringToWString(rowName) , 7)
    else
        ButtonSetText(buttonName, L"" )
    end
    
    
    -- Name
    LabelSetText(rowName.."Name", itemData.name)
    color = DataUtils.GetItemRarityColor(itemData)
    LabelSetTextColor( rowName.."Name", color.r, color.g, color.b )
    
    
    -- Rank
    
    -- NOTE: for Trade Skill items, we may also want to display
    --   skill level and tint accordingly
    --local meetsTradeSkillLevel = DataUtils.PlayerTradeSkillLevelIsEnoughForItem( itemData )

    LabelSetText (rowName.."Rank", L""..itemData.level)
    
    local meetsRankRequirement  = DataUtils.LevelIsEnoughForItem( GameData.Player.level, itemData )
    if meetsRankRequirement then
        color = AuctionListWindow.COLOR_MEETS_REQUIREMENTS
    else
        color = AuctionListWindow.COLOR_FAILS_REQUIREMENTS
    end
    LabelSetTextColor (rowName.."Rank", color.r, color.g, color.b)

    
    -- Duration
    local timeLeftText = AuctionListWindow.GetTextForTimeLeft( auctionData.timeLeft )
    LabelSetText( rowName.."Duration", timeLeftText )
    
    -- Seller
    -- for some search windows, we want to replace auctionData.sellerName
    --     with auctionData.highBidderName, e.g. "My Auctions tab"
	local myAuctionPaneShowing = AuctionListDataManager.IsMyAuctionsPaneShowing()
	if AuctionListDataManager.GetCurrentTabNumber() == AuctionHouseWindow.TAB_BROWSE_ID then
		LabelSetText( rowName.."Seller", auctionData.sellerName )
    else
		LabelSetText( rowName.."Seller", auctionData.highBidderName )
    end
    
    -- BidPrice
    -- TODO: We may want the ability to have only a buyOut, in which case we should
    --      hide the MoneyFrame and simply put up a "-"
    if AuctionListWindow.HideBidPriceIfBuyOnly and auctionData.currentBid == auctionData.buyOutPrice then
		MoneyFrame.FormatMoney (rowName.."BidPrice", 0, MoneyFrame.HIDE_EMPTY_WINDOWS)
	else
		MoneyFrame.FormatMoney (rowName.."BidPrice", auctionData.currentBid, MoneyFrame.HIDE_EMPTY_WINDOWS_ABOVE_VALUE) -- MoneyFrame.HIDE_EMPTY_WINDOWS)
	end

    -- show additional text next to the bid price in the player is the high bidder
    local name = L""
    if auctionData.highBidderName == GameData.Player.name then
		name = AuctionListWindow.playerIsHighBidderText
	end
	LabelSetText( rowName.."HighBidder", name )
	WindowSetShowing( rowName.."HighBidder", (auctionData.highBidderName == GameData.Player.name) ) 
	
    
    -- BuyOutPrice
    -- TODO: We may want the ability to have only a bid price, in which case we should
    --      hide the MoneyFrame and simply put up a "-"
    MoneyFrame.FormatMoney (rowName.."BuyOutPrice", auctionData.buyOutPrice, MoneyFrame.HIDE_EMPTY_WINDOWS_ABOVE_VALUE) --MoneyFrame.HIDE_EMPTY_WINDOWS)

end


function AuctionListWindow.GetTextForTimeLeft( timeRemaining )
    
    local index = AuctionListWindow.GetTimeLeftIndex( timeRemaining )

    if index == ALW.TimeLeftValueNotFound  then
        return AuctionListWindow.DefaultTimeLeftText
    else
        return AuctionListWindow.TimeLeft[index].text
    end
end


function AuctionListWindow.GetTooltipForTimeLeft( timeRemaining )
SendDebug(L"AuctionListWindow.GetTooltipForTimeLeft timeRemaining="..timeRemaining, 7 )

    local index = AuctionListWindow.GetTimeLeftIndex( timeRemaining )

    if index == ALW.TimeLeftValueNotFound then
        return AuctionListWindow.DefaultTimeLeftTooltip
    else
        return AuctionListWindow.TimeLeft[index].tooltip
    end
end


function AuctionListWindow.GetTimeLeftIndex( timeRemaining )

    for index, data in ipairs( AuctionListWindow.TimeLeft ) do
        if timeRemaining == data.value then
            return index
        end
    end
    
    return ALW.TimeLeftValueNotFound 
end

function AuctionListWindow.Shutdown()

end

function AuctionListWindow.OnShown()
SendDebug(L"AuctionListWindow.OnShown")

	AuctionListWindow.InitializeTimeLeftValues()
    --WindowUtils.OnShown()
    AuctionListWindow.Clear()
	MoneyFrame.RegisterCallbackForValueChanged( windowName.."BrowseOptionsMyBidPrice", AuctionListWindow.OnMyBidChanged )
end

function AuctionListWindow.OnHidden()
SendDebug(L"AuctionListWindow.OnHidden")
    MoneyFrame.UnregisterCallbackForValueChanged( windowName.."BrowseOptionsMyBidPrice" )
    --WindowUtils.OnHidden()
    AuctionListWindow.Clear()
end


function AuctionListWindow.OnRowSelected()
SendDebug(L"AuctionListWindow.OnRowSelected")

    local rowNum = WindowGetId( SystemData.ActiveWindow.name )
    local dataIndex = ListBoxGetDataIndex( windowName.."List", rowNum )
    dataIndex = dataIndex or 0
    AuctionListWindow.UpdateSelectedRow( dataIndex )
end
    

function AuctionListWindow.Clear()
SendDebug(L"AuctionListWindow.Clear")
	
    AuctionListDataManager.Clear()
    
    ListBoxSetDisplayOrder( windowName.."List", {} )
        
    AuctionListWindow.ClearSortButton() 
    
    AuctionListWindow.UpdateSelectedRow( 0 )
end


function AuctionListWindow.UpdateSelectedRow( rowNum )
SendDebug(L"AuctionListWindow.UpdateSelectedRow")
SendDebug(L" rowNum as string = "..StringToWString( tostring(rowNum) ) )
    
	local windowData = AuctionListDataManager.GetCurrentWindowData()
	
	-- unselect previous row, if it's not already cleared or a no longer existing row
	if windowData.currentlySelectedRowName ~= "" and DoesWindowExist(windowData.currentlySelectedRowName) then
	
        SendDebug(L"  unselecting "..StringToWString(windowData.currentlySelectedRowName) )
        ButtonSetPressedFlag( windowData.currentlySelectedRowName, false )
        ButtonSetStayDownFlag( windowData.currentlySelectedRowName, false )
	    windowData.currentlySelectedRowName = ""
	end
	
	-- if we clicked on a new row, then we mark it as selected
    if rowNum == 0 or windowData.currentlySelectedRow == rowNum then
        windowData.currentlySelectedRow  = 0
        windowData.currentlySelectedRowName = ""
    else                
        windowData.currentlySelectedRow = rowNum
	    windowData.currentlySelectedRowName = SystemData.ActiveWindow.name
        ButtonSetPressedFlag( windowData.currentlySelectedRowName,  true)
        ButtonSetStayDownFlag( windowData.currentlySelectedRowName, true)
    end
    
    
    local auctionData = windowData.searchResultsData[rowNum]
    
    if auctionData == nil or isMyOwnAuction then
SendDebug(L"  windowData.myBid = 0")
        AuctionListWindow.ClearMyBid()
    else
SendDebug(L"  AuctionListWindow.UpdateMyBidToMinimumBid")
		local hasBidsAlready = (auctionData.highBidderName ~= L"")
        AuctionListWindow.UpdateMyBidToMinimumBid( auctionData.currentBid, auctionData.buyOutPrice, hasBidsAlready )
    end
    
    AuctionListWindow.UpdateButtons()    
end


-- clears the column header sort arrow if set
function AuctionListWindow.ClearSortButton()
SendDebug(L"AuctionListWindow.ClearSortButton")

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    
    if windowData.sortColumnName ~= "" then
        WindowSetShowing(windowData.sortColumnName.."DownArrow", false )
        WindowSetShowing(windowData.sortColumnName.."UpArrow", false )
        
        windowData.sortColumnName = "" 
        windowData.sortColumnNum = 0
    end
    
end


-- Update the sort buttons
function AuctionListWindow.ChangeSorting()
SendDebug(L"AuctionListWindow.ChangeSorting", 7)

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    
    if windowData.sortColumnName == SystemData.ActiveWindow.name then
    
SendDebug(L"   toggling sorting", 7)
        windowData.shouldSortIncresing = (not windowData.shouldSortIncresing)

    else
 
SendDebug(L"   windowData.shouldSortIncresing = ALW.DEFAULT_SORTING", 7)
        AuctionListWindow.ClearSortButton()
        windowData.sortColumnName = SystemData.ActiveWindow.name
        windowData.sortColumnNum = WindowGetId( SystemData.ActiveWindow.name )
        windowData.shouldSortIncresing = ALW.DEFAULT_SORTING
    end
    
SendDebug(L"   windowData.sortColumnName == "..StringToWString(windowData.sortColumnName))

    WindowSetShowing(windowData.sortColumnName.."DownArrow", windowData.shouldSortIncresing )
    WindowSetShowing(windowData.sortColumnName.."UpArrow", (not windowData.shouldSortIncresing) )
   
    AuctionListWindow.Sort()
    
    AuctionListWindow.DisplayCurrentWindowData()    
end


-- returns true if a sort column is set and false if not
function AuctionListWindow.Sort()

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local comparator = windowData.columnData[windowData.sortColumnNum].sortFunc
    table.sort( windowData.searchResultsData, comparator )

    -- TODO: preserve row in the future even after it has moved
    AuctionListWindow.UpdateSelectedRow( 0 )
end

function AuctionListWindow.SetListRowTints()

    local numVisibleRows = AuctionListWindow.MAX_VISIBLE_ROWS
    local listBoxName = windowName.."List"
	DataUtils.SetListRowAlternatingTints( listBoxName, numVisibleRows )

    
end


function AuctionListWindow.Show()
SendDebug(L"AuctionListWindow.Show")

    WindowSetShowing( windowName, true )
    AuctionListWindow.UpdateMoneyAvailable()
end

function AuctionListWindow.Hide()
SendDebug(L"AuctionListWindow.Hide")
    WindowSetShowing( windowName, false )
end

function AuctionListWindow.ToggleShowing()
SendDebug(L"AuctionListWindow.ToggleShowing")

    if ( AuctionListWindow.IsShowing() == true ) then
        AuctionListWindow.Hide()
    else
        AuctionListWindow.Show()
    end
end

function AuctionListWindow.IsShowing()
SendDebug(L"AuctionListWindow.IsShowing")
    return WindowGetShowing( windowName )
end

function AuctionListWindow.IsTitleShowing()
SendDebug(L"AuctionListWindow.IsTitleShowing")
    return WindowGetShowing( windowName.."Title" )
end

function AuctionListWindow.UpdateMoneyAvailable()
--SendDebug(L"AuctionListWindow.UpdateMoneyAvailable")

    if AuctionListWindow.IsShowing() then
        MoneyFrame.FormatMoney (windowName.."BrowseOptionsMoneyAvailable", Player.GetMoney(), MoneyFrame.HIDE_EMPTY_WINDOWS)  --MoneyFrame.SHOW_EMPTY_WINDOWS )
    end
    
    AuctionListWindow.UpdateButtons()
end

function AuctionListWindow.OnMouseOverIcon()
--SendDebug(L"AuctionListWindow.OnMouseOverIcon")
	
	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local rowNum = WindowGetId( SystemData.MouseOverWindow.name )
    local dataIndex = ListBoxGetDataIndex( windowName.."List", rowNum )
    if dataIndex == 0 or 
       windowData.searchResultsData[dataIndex] == nil or 
       windowData.searchResultsData[dataIndex].itemData == nil then
       
        return
    end
    
	local itemData = windowData.searchResultsData[dataIndex].itemData 
	Tooltips.CreateItemTooltip (itemData, SystemData.ActiveWindow.name, Tooltips.ANCHOR_WINDOW_TOP )

end 

function AuctionListWindow.OnMouseOverDuration()
SendDebug(L"AuctionListWindow.OnMouseOverDuration", 7)
	
	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local rowNum = WindowGetId( SystemData.MouseOverWindow.name )
    local dataIndex = ListBoxGetDataIndex( windowName.."List", rowNum )
    
    local auctionData = windowData.searchResultsData[dataIndex]
    
    if auctionData ~= nil then
		
	SendDebug(L"  auctionData ~= nil dataIndex="..dataIndex, 7)
		local text = AuctionListWindow.GetTooltipForTimeLeft( auctionData.timeLeft )
		Tooltips.CreateTextOnlyTooltip( SystemData.MouseOverWindow.name, text )
		Tooltips.AnchorTooltip( Tooltips.ANCHOR_WINDOW_TOP )
		
SendDebug(L"  text="..text, 7 )
    end

end 

function AuctionListWindow.HandleMouseWheel()
SendDebug(L"AuctionListWindow.HandleMouseWheel")
	

end 

-- TODO: we should autocorrect out of bounds changes to MyBid, but only if 
--   active window is not any of 3 editable fields
function AuctionListWindow.OnMyBidChanged()
SendDebug(L"AuctionListWindow.OnMyBidChanged")
	
	AuctionListWindow.UpdateButtons()
end 

--[[
function AuctionListWindow.CorrectMyBidIfNeeded()
SendDebug(L"AuctionListWindow.CorrectMyBidIfNeeded")


end 

function AuctionListWindow.IsMyBidTooLow()
SendDebug(L"AuctionListWindow.IsMyBidTooLow")
	
	

end 

function AuctionListWindow.IsMyBidTooHigh()
SendDebug(L"AuctionListWindow.IsMyBidTooHigh")
	
	

end
--]]

function AuctionListWindow.ClearMyBid()
SendDebug(L"AuctionListWindow.ClearMyBid")
	
	local windowData = AuctionListDataManager.GetCurrentWindowData()
    windowData.myBid = 0
    MoneyFrame.FormatMoney( windowName.."BrowseOptionsMyBidPrice", windowData.myBid, MoneyFrame.SHOW_EMPTY_WINDOWS )
end

function AuctionListWindow.UpdateMyBidToMinimumBid( currentBid, buyOutPrice, hasBidsAlready )
SendDebug(L"AuctionListWindow.UpdateMyBidToMinimumBid")
SendDebug(L"   currentBid = "..currentBid..L"   buyOutPrice = "..buyOutPrice)

	local windowData = AuctionListDataManager.GetCurrentWindowData()
        
    if hasBidsAlready then
		windowData.myBid = AuctionListWindow.GetNextMinimumBid( currentBid, buyOutPrice )  
    else
		windowData.myBid = currentBid
	end
    
SendDebug(L"   myBid = "..windowData.myBid)
    MoneyFrame.FormatMoney( windowName.."BrowseOptionsMyBidPrice", windowData.myBid, MoneyFrame.SHOW_EMPTY_WINDOWS )
end

function AuctionListWindow.GetNextMinimumBid( currentBid, buyOutPrice )
SendDebug(L"AuctionListWindow.GetNextMinimumBid")
SendDebug(L"   currentBid = "..currentBid..L"   buyOutPrice = "..buyOutPrice)

    local increaseToBid = math.ceil(currentBid * AuctionListWindow.MIN_BID_MULTIPLIER)
    if increaseToBid < AuctionListWindow.MIN_BID_INCREMENT then
        increaseToBid = AuctionListWindow.MIN_BID_INCREMENT
    end
    
    local minimumBid = currentBid + increaseToBid
    
    -- check if bidding would cost more than buying
    --   or we may also have "buy only" auctions. i.e. currentBid == buyOutPrice
    -- Note: buyOutPrice == 0 means there isn't a buyOutPrice so ignore it
    if buyOutPrice > 0 and minimumBid > buyOutPrice then
        minimumBid = buyOutPrice
    end  
    
    return minimumBid
end


function AuctionListWindow.UpdateButtons()
SendDebug(L"AuctionListWindow.UpdateButtons")

	local windowData = AuctionListDataManager.GetCurrentWindowData()
	if windowData == nil or windowData.searchResultsData == nil then
	
		DEBUG(L"ERROR in AuctionListWindow.UpdateButtons: - AuctionListDataManager not initialized")
		return
	end
	
	if AuctionListDataManager.IsMyAuctionsPaneShowing() then
		AuctionListWindow.UpdateMyAuctionsButtons()
	else
		AuctionListWindow.UpdateBidBuyButtons()
	end
end


function AuctionListWindow.UpdateMyAuctionsButtons()
SendDebug(L"AuctionListWindow.UpdateMyAuctionsButtons", 7)

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local auctionData = windowData.searchResultsData[windowData.currentlySelectedRow]

    local bidderFound = true
    if auctionData == nil then
    
		LabelSetText( windowName.."MyAuctionsOptionsHelpText", AuctionListWindow.myAuctionDefaultText )
		ButtonSetDisabledFlag( windowName.."MyAuctionsOptionsCancelButton", true ) 
    elseif auctionData.highBidderName  == nil or auctionData.highBidderName  == L"" then 
    
		LabelSetText( windowName.."MyAuctionsOptionsHelpText", AuctionListWindow.myAuctionCancelText )
		ButtonSetDisabledFlag( windowName.."MyAuctionsOptionsCancelButton", false )
    else
    
		LabelSetText( windowName.."MyAuctionsOptionsHelpText", AuctionListWindow.myAuctionNoCancelText )
		ButtonSetDisabledFlag( windowName.."MyAuctionsOptionsCancelButton", true )
	end
    
end

-- TODO: it would be great if this returned true for other characters owned by this Player's account (on this server)
function AuctionListWindow.IsMyAuction( auctionData )

	return auctionData.sellerName ~= nil and auctionData.sellerName == GameData.Player.name
end

function AuctionListWindow.UpdateBidBuyButtons()
SendDebug(L"AuctionListWindow.UpdateBidBuyButtons", 7)

    local bidButtonDisabled, buyOutButtonDisabled = true, true
	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local auctionData = windowData.searchResultsData[windowData.currentlySelectedRow]
    
    -- verify that the auction isn't your own
    local isBiddableAuction = (auctionData ~= nil and not AuctionListWindow.IsMyAuction( auctionData ) )
    
    if isBiddableAuction then
    
        windowData.myBid = MoneyFrame.ConvertCurrencyToBrass( windowName.."BrowseOptionsMyBidPrice" )
        
        local playerMoney = Player.GetMoney()
        if auctionData.buyOutPrice > 0 and playerMoney >= auctionData.buyOutPrice then
            bidButtonDisabled, buyOutButtonDisabled = false, false   
        elseif playerMoney >= windowData.myBid then
            bidButtonDisabled = false
        end
        
		if windowData.myBid == auctionData.buyOutPrice or 
		   (auctionData.buyOutPrice > 0 and windowData.myBid >= auctionData.buyOutPrice) then
		   
			bidButtonDisabled = true
		end
    
    end
        
    ButtonSetDisabledFlag( windowName.."BrowseOptionsBidButton", bidButtonDisabled )
    ButtonSetDisabledFlag( windowName.."BrowseOptionsBuyOutButton", buyOutButtonDisabled )
end




function AuctionListWindow.OnBidButtonPressed()
SendDebug(L"AuctionListWindow.OnBidButtonPressed")

	-- TEMP: TODO: This only needs to be called because 
	--   we currently are not correcting the buttons (and windowData.myBid) 
	--   after we change the bid price    
	--AuctionListWindow.OnMyBidChanged()

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local auctionData = windowData.searchResultsData[windowData.currentlySelectedRow]

    if auctionData == nil or ButtonGetDisabledFlag( windowName.."BrowseOptionsBidButton" )== true then
        return
    end
    
    if auctionData.buyOutPrice > 0 and windowData.myBid >= auctionData.buyOutPrice then
        AuctionListWindow.OnBuyOutButtonPressed()
    else
		AuctionListWindow.SendAuctionBidItem( auctionData, windowData.myBid, false )
    end
	
    ButtonSetPressedFlag( windowName.."BrowseOptionsBidButton", false )
end

function AuctionListWindow.OnBuyOutButtonPressed()
SendDebug(L"AuctionListWindow.OnBuyOutButtonPressed", 7)
    
	-- TEMP: TODO: This only needs to be called because 
	--   we currently are not correcting the buttons after we change the bid price    
	--AuctionListWindow.OnMyBidChanged()
	--SendDebug(L"AuctionListWindow.OnMyBidChanged", 7)

	local windowData = AuctionListDataManager.GetCurrentWindowData()
	local auctionData = windowData.searchResultsData[windowData.currentlySelectedRow]
    
    if auctionData == nil or ButtonGetDisabledFlag( windowName.."BrowseOptionsBuyOutButton" )== true then
        return
    end
    
    AuctionListWindow.SendAuctionBidItem( auctionData, auctionData.buyOutPrice, true )
    
SendDebug(L"  calling ButtonSetPressedFlag", 7)
    ButtonSetPressedFlag( windowName.."BrowseOptionsBuyOutButton", false )
end

function AuctionListWindow.SendAuctionBidItem( auctionData, bidPrice, IsBuyout )
SendDebug(L"AuctionListWindow.SendAuctionBidItem")
    
	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local auctionData = windowData.searchResultsData[windowData.currentlySelectedRow]
    
    if Player.GetMoney() < bidPrice then
        AuctionListWindow.DisplayError( AuctionListWindow.errorInsufficientFundsText )
        return
    end
    
	if AuctionListWindow.REQUEST_TEST_RESULTS_ON then
	-- TESTING: DEBUG: 

		-- BidOnAuction takes 2 additional parameters for testing:
		local fakeResultData = true
		local desiredResult = GameData.Auction.BID_SUCCESS 
		
		if IsBuyout then
			desiredResult = GameData.Auction.BUYOUT_SUCCESS 
		end

	SendDebug( L"  calling BidOnAuction, requesting fake results, auction # "..auctionData.auctionIDHigherNum..L" "..auctionData.auctionIDLowerNum..L"  rev = "..auctionData.revision..L"  bidPrice = "..bidPrice..L"  desiredResult = "..desiredResult, 7)
		
		BidOnAuction( auctionData.auctionIDHigherNum, auctionData.auctionIDLowerNum, auctionData.revision, bidPrice, IsBuyout, fakeResultData, desiredResult )
	   
	-- END TESTING: DEBUG:
	else
	SendDebug( L" calling BidOnAuction  auction # "..auctionData.auctionIDHigherNum..L" "..auctionData.auctionIDLowerNum..L"  bidPrice = "..bidPrice, 7)

		BidOnAuction( auctionData.auctionIDHigherNum, auctionData.auctionIDLowerNum, auctionData.revision, bidPrice, IsBuyout )
	end

    -- TODO: remove row or display that' you're making bid on it
    AuctionListWindow.UpdateSelectedRow( 0 )
    --AuctionListWindow.ClearMyBid()
end



function AuctionListWindow.OnCancelButtonPressed()
	SendDebug(L"OnCancelButtonPressed", 6)

    if ButtonGetDisabledFlag( windowName.."MyAuctionsOptionsCancelButton" )== true then
        return
    end
    
    -- display a confirmation dialog before cancelling
  DialogManager.MakeTwoButtonDialog (AuctionListWindow.warnBeforeCancellingText, 
                                    GetString (StringTables.Default.LABEL_YES), AuctionListWindow.CancelPressConfirmed, 
                                    GetString (StringTables.Default.LABEL_NO), nil,
                                    nil, nil, false, nil, nil)

end


-- send cancel info to server
function AuctionListWindow.CancelPressConfirmed()
	SendDebug(L"CancelPressConfirmed", 6)

	local windowData = AuctionListDataManager.GetCurrentWindowData()
    local auctionData = windowData.searchResultsData[windowData.currentlySelectedRow]

    if auctionData == nil or ButtonGetDisabledFlag( windowName.."MyAuctionsOptionsCancelButton" )== true then
        return
    end
    
	if AuctionListWindow.REQUEST_TEST_RESULTS_ON then
-- TESTING: DEBUG: 
	
		-- CancelAuction takes 2 additional parameters for testing:
		local fakeResultData = true
		local desiredResult = GameData.Auction.CANCEL_SUCCESS 
	    
		CancelAuction( auctionData.auctionIDHigherNum, auctionData.auctionIDLowerNum, auctionData.revision, fakeResultData, desiredResult )
  
-- END TESTING: DEBUG: 
	else	  
		CancelAuction( auctionData.auctionIDHigherNum, auctionData.auctionIDLowerNum, auctionData.revision )
	end
	
end


function AuctionListWindow.ReceivedBidResult( resultData )
SendDebug(L"AuctionListWindow.ReceivedBidResult", 7)

	if resultData == nil then
		ERROR(L"AuctionListWindow.ReceivedBidResult ERROR: resultData is nil")
		return
	end
	
SendDebug(L"   status = "..resultData.result..L"   auction # "..resultData.auctionIDHigherNum..L" "..resultData.auctionIDLowerNum..L"  revision = "..resultData.revision..L"  currentBid = "..resultData.currentBid, 8)
	
	if resultData.result == GameData.Auction.BID_SUCCESS then
		SendDebug(L"   BID_SUCCESS", 7)
		
		-- successful bid, update value
		AuctionListWindow.UpdateAuctionBidPrice( resultData.auctionIDHigherNum, resultData.auctionIDLowerNum, resultData.revision, resultData.currentBid, true )

	elseif resultData.result == GameData.Auction.BUYOUT_SUCCESS or  
		   resultData.result == GameData.Auction.CANCEL_SUCCESS then
		   
		SendDebug(L"   BUYOUT/CANCEL SUCCESS", 7)
		
		-- successful buyout, remove from auction list
		AuctionListWindow.RemoveAuctionFromSearchResults( resultData.auctionIDHigherNum, resultData.auctionIDLowerNum )

	elseif resultData.result ==  GameData.Auction.BID_FAIL_BAD_BID_PRICE or
		   resultData.result ==  GameData.Auction.BID_FAIL_BAD_BUY_OUT_PRICE or
		   resultData.result ==  GameData.Auction.BID_FAIL_OTHER_IS_BIDDING or
		   resultData.result ==  GameData.Auction.BID_FAIL_UNKNOWN_REASON or
		   resultData.result ==  GameData.Auction.CANCEL_FAIL_BIDDER_EXISTS or
		   resultData.result ==  GameData.Auction.CANCEL_FAIL_NOT_OWNER or
		   resultData.result ==  GameData.Auction.UNKNOWN_REASON or
		   resultData.result ==  GameData.Auction.CANCEL_FAIL_UNKNOWN_REASON then
		   
		SendDebug(L"   failed but auction still exists", 7)
		AuctionListWindow.UpdateAuctionBidPrice( resultData.auctionIDHigherNum, resultData.auctionIDLowerNum, resultData.revision, resultData.currentBid, false )

	elseif resultData.result ==  GameData.Auction.BID_FAIL_MISSING_ITEM or
		   resultData.result ==  GameData.Auction.BID_FAIL_ITEM_SOLD or
		   resultData.result ==  GameData.Auction.CANCEL_FAIL_ITEM_SOLD then
		   
		SendDebug(L"   failed and item no longer there", 7)
		AuctionListWindow.RemoveAuctionFromSearchResults( resultData.auctionIDHigherNum, resultData.auctionIDLowerNum )
	
	elseif resultData.result ==  GameData.Auction.SERVER_UNAVAILABLE then
		AuctionHouseWindow.DisplayUnrecoverableError( AuctionListWindow.errorServerUnavailableText )
		
	elseif resultData.result ==  GameData.Auction.CREATE_AUCTION_FAILED then
		ERROR( L"Create Auction failed." )
		
	else
		ERROR( L"AuctionListWindow.ReceivedBidResult ERROR: unknown result value = "..resultData.result )
	end

    --AuctionListWindow.DisplayError( errorMsg )
end


-- TODO: this probably needs to look at all windows
function AuctionListWindow.GetAuctionDataFromSearchResults( auctionIDHigherNum, auctionIDLowerNum )
SendDebug(L"AuctionListWindow.GetAuctionDataFromSearchResults", 7)

	-- **** TODO *** this needs to handle the auction referenced being in a tab other than the current tab, 
	--		in multiple tabs, or in none of the current tabs 
	
	local windowData = AuctionListDataManager.GetCurrentWindowData()
	
    for i, auctionData in ipairs(windowData.searchResultsData) do  
		if auctionData.auctionIDLowerNum == auctionIDLowerNum and auctionData.auctionIDHigherNum == auctionIDHigherNum then
SendDebug(L"   found auctionIDLowerNum="..auctionIDLowerNum..L"  at pos="..i, 7)
			return auctionData, i
		end
    end
    
    SendDebug(L" auction not found", 7)
	return nil
end

-- TODO: this probably needs to look at all windows
function AuctionListWindow.RemoveAuctionFromSearchResults( auctionIDHigherNum, auctionIDLowerNum )
SendDebug(L"AuctionListWindow.RemoveAuctionFromSearchResults")

	-- **** TODO *** this needs to handle the auction referenced being in a tab other than the current tab, 
	--		in multiple tabs, or in none of the current tabs 
	local auctionInfo, auctionIndex = AuctionListWindow.GetAuctionDataFromSearchResults( auctionIDHigherNum, auctionIDLowerNum )
	if auctionInfo == nil then
		return
	end
	
SendDebug(L"   Removing auctionIndex = "..auctionIndex)

	local windowData = AuctionListDataManager.GetCurrentWindowData()

	table.remove( windowData.searchResultsData, auctionIndex )
	--AuctionListWindow.Populate()
	AuctionListWindow.OnSearchResultsReceived( windowData.searchResultsData )
end

--[[
-- returns false if auction ID not found in current auctions list
function AuctionListWindow.RemoveAuctionFromSearchResults( auctionIDHigherNum, auctionIDLowerNum )
SendDebug(L"AuctionListWindow.GetAuctionDataFromSearchResults")

    for i, auctionData in ipairs(windowData.searchResultsData) do  
		if auctionData.auctionIDLowerNum == auctionIDLowerNum and auctionData.auctionIDHigherNum == auctionIDHigherNum then
			table.remove( windowData.searchResultsData, i )
			--AuctionListWindow.Populate()
			AuctionListWindow.OnSearchResultsReceived( windowData.searchResultsData )
			return true
		end
    end
    
	return false
end
--]]

-- TODO: need to change this to check all tabs
-- returns false if auction ID not found in current auctions list
function AuctionListWindow.UpdateAuctionBidPrice( auctionIDHigherNum, auctionIDLowerNum, revision, newBidPrice, markAsHighBidder )
SendDebug(L"AuctionListWindow.UpdateAuctionBidPrice", 7)


	-- check and see if we even still have that auction in our results data
	
	-- **** TODO *** this needs to handle the auction referenced being in a tab other than the current tab, 
	--		in multiple tabs, or in none of the current tabs 
	local auctionData, auctionIndex = AuctionListWindow.GetAuctionDataFromSearchResults( auctionIDHigherNum, auctionIDLowerNum )
	if auctionData == nil then
		return
	end

	auctionData.currentBid = newBidPrice 
	auctionData.revision = revision
	
    if markAsHighBidder then
		SendDebug(L"markAsHighBidder == true", 7)
		auctionData.highBidderName = GameData.Player.name
    end
	
	local windowData = AuctionListDataManager.GetCurrentWindowData()
	AuctionListWindow.OnSearchResultsReceived( windowData.searchResultsData )
end


function AuctionListWindow.DisplayError( errorMsg )
SendDebug(L"AuctionListWindow.DisplayError")

    local okayText = GetString (StringTables.Default.LABEL_OKAY)
    DialogManager.MakeOneButtonDialog( errorMsg, okayText)  
end


function AuctionListWindow.ClearCurrentResults()
SendDebug(L"AuctionListWindow.ClearCurrentResults")

    ListBoxSetDisplayOrder( windowName.."List", {} )
    WindowSetShowing( windowName.."NoResultsText", false )
end
